package com.umpay.sp.saas.action.batchNet;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.struts2.ServletActionContext;


import com.opensymphony.xwork2.Preparable;
import com.umpay.operation.common.ReqMessage;
import com.umpay.operation.common.ResMessage;
import com.umpay.sp.saas.util.DataEntryUtil;
import com.umpay.sp.saas.util.ReqMessageUtil;
import com.umpay.sp.saas.util.ValidateUtil;
import com.umpay.sp.util.StringUtil;
import com.umpay.sp.web.action.sys.BaseAction;
import com.umpay.sp.web.util.FileUtil;
import com.umpay.sp.web.util.PropertyUtil;
/**
 * 立马付批量入网Action
 * @author ChenFuLong
 * 
 */
public class BatchNetAction extends BaseAction implements Preparable{

	private static final long serialVersionUID = -4517942154165478931L;
	private String fileFullName;
	private String fileName;
	private File uploadify;//用于上传
	private String uploadifyFileName;
	HttpServletRequest request = ServletActionContext.getRequest();
	HttpServletResponse response=ServletActionContext.getResponse();

	public void prepare() throws Exception {}
	
	
	/**
	 * 跳转到文件上传页面
	 */
	public String batchdNetUploadView(){
		return "batchdNetUpload";
	}
	
	/**
	 * 下载Excel模板
	 * @return
	 */
	public String downLoad(){
		String batchNetFilePath = StringUtil.trim(PropertyUtil.getStrValue("spEnterpriseWeb_config.properties","batchNet.scfile.path", ""));
		log.info("【下载Excel模板】" + batchNetFilePath + this.getFileName());
		File file = new File(batchNetFilePath, this.getFileName().toString());
		try {
			FileUtil.downLoadZipFile(file, request, response);
		} catch (Exception e) {
			log.error("【下载Excel模板】异常", e);
			errorMessage = "Excel模板文件下载失败";
			return ERROR;
		}
		return null;
	}

	
	/**
	 * 上传Excel文件（批量入网）
	 * @throws IOException
	 */
	public void doUploadfile() throws IOException {
		HSSFWorkbook wb = null;
		String agentId= StringUtil.trim(this.getSession().get("agentId"));
		String fileFullName = uploadifyFileName;//文件名全称，带扩展名
		String fileName = fileFullName.substring(0,fileFullName.lastIndexOf("."));
		//【1】校验模板（扩展名）
		if (!fileFullName.substring(fileFullName.lastIndexOf(".xls")).equalsIgnoreCase(".xls")) {
			log.info("【上传Excel文件】扩展名错误" + fileFullName);
			response.getWriter().write("0001");
			return;
		}
		try {
			//【2】校验批次号（文件名）
			Map<String, String> batchNo = ValidateUtil.batchNo(agentId, fileName);
			if (!"0000".equals(batchNo.get("retCode"))) {
				response.getWriter().write(batchNo.get("retCode"));
				return;
			}
			
			//获取上传的文件
			FileInputStream fi = new FileInputStream(uploadify);
			wb = new HSSFWorkbook(fi);
			HSSFSheet sheet = wb.getSheetAt(0);
			
			//【3】校验文件行数
			int row = sheet.getLastRowNum();//Excel文件中的行数（第一行是标题，所以不用加1）
			if (row < 1) {
				log.info("【上传Excel文件】EXCEL中条数为0");
				response.getWriter().write("0003");
				return;
			}
			String maxRows = PropertyUtil.getStrValue("spEnterpriseWeb_config.properties","maxRows", "100");//配置文件中的最大行数
			if (row > Integer.valueOf(maxRows)) {
				log.info("【上传Excel文件】超过最大条数限制" + "配置" + maxRows + "文件" + row);
				response.getWriter().write("row" + maxRows);
				return;
			}
			
			//【4】校验Excel模板
			Map<String, String> template = ValidateUtil.template(sheet);
			if (!"0000".equals(template.get("retCode"))) {
				response.getWriter().write(template.get("retCode"));
				return;
			}
			
			//【5】保存批次信息
			ReqMessage req = ReqMessageUtil.makeOpReq();
			req.put("batchNo",agentId + "_" + fileName);//批量号
			req.put("totalCnt",row);//总条数 
			req.put("state","1");//状态：0已完成；1处理中；2批次待处理
			req.put("uploadUserId",agentId);//上传人
			req.put("invalidCnt","0");//无效条数
			req.put("endTime","");//结束时间
			ResMessage res = DataEntryUtil.saveBatch(req);
			if (!"0000".equals(res.getRetCode())) {
				response.getWriter().write("1111");
				return;
			}
			
			//【6】开启一个线程处理Excel中的数据
			Thread thread = new BatchNetThread(sheet, agentId + "_" + fileName.replace(".xls", ""));
			log.info("【上传Excel文件】开启线程处理");
			thread.start();
			
			response.getWriter().write("0000");
		} catch (Exception e) {
			log.error("【上传Excel文件】异常", e);
			response.getWriter().write("1111");
			return;
		}
	}
	
	public String getFileName() {
		return fileName;
	}

	public void setFileName(String fileName) {
		this.fileName = fileName;
	}

	public File getUploadify() {
		return uploadify;
	}

	public void setUploadify(File uploadify) {
		this.uploadify = uploadify;
	}

	public String getUploadifyFileName() {
		return uploadifyFileName;
	}

	public void setUploadifyFileName(String uploadifyFileName) {
		this.uploadifyFileName = uploadifyFileName;
	}

	public HttpServletRequest getRequest() {
		return request;
	}

	public void setRequest(HttpServletRequest request) {
		this.request = request;
	}

	public HttpServletResponse getResponse() {
		return response;
	}

	public void setResponse(HttpServletResponse response) {
		this.response = response;
	}


	public String getFileFullName() {
		return fileFullName;
	}


	public void setFileFullName(String fileFullName) {
		this.fileFullName = fileFullName;
	}

}
